"""视频导入视图模块"""
import os
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                             QPushButton, QFileDialog, QProgressBar, QListWidget,
                             QListWidgetItem, QMessageBox)
from PyQt6.QtCore import Qt, pyqtSignal, QThread
from PyQt6.QtGui import QIcon, QDragEnterEvent, QDropEvent
from src.ui.styles import (BUTTON_STYLE, INPUT_STYLE, LABEL_STYLE,
                      PROGRESS_BAR_STYLE, SCROLL_BAR_STYLE, SECTION_TITLE_STYLE, LIST_WIDGET_STYLE, MESSAGEBOX_STYLE)
from src.video_processor import VideoProcessor

class VideoLoadWorker(QThread):
    progress_updated = pyqtSignal(int)
    loading_finished = pyqtSignal(str)
    error_occurred = pyqtSignal(str)
    
    def __init__(self, video_path):
        super().__init__()
        self.video_path = video_path
        
    def run(self):
        try:
            processor = VideoProcessor()
            processor.load_video(self.video_path)
            self.loading_finished.emit(self.video_path)
        except Exception as e:
            self.error_occurred.emit(str(e))

class VideoImportView(QWidget):
    """视频导入视图类"""
    
    # 自定义信号
    video_imported = pyqtSignal(str)  # 视频导入完成信号
    video_loaded = pyqtSignal(str)
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("视频导入")
        self._init_ui()
        self._apply_styles()
        
    def _init_ui(self):
        """初始化UI组件"""
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)
        
        # 创建拖放区域
        self._create_drop_area(main_layout)
        
        # 创建视频列表
        self._create_video_list(main_layout)
        
        # 创建底部按钮
        self._create_bottom_buttons(main_layout)
        
    def _create_drop_area(self, parent_layout):
        """创建拖放区域"""
        drop_layout = QVBoxLayout()
        drop_layout.setContentsMargins(0, 0, 0, 0)
        drop_layout.setSpacing(10)
        
        # 提示标签
        hint_label = QLabel("将视频文件拖放到此处，或点击选择文件")
        hint_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        drop_layout.addWidget(hint_label)
        
        # 选择文件按钮
        select_btn = QPushButton("选择文件")
        select_btn.clicked.connect(self._select_files)
        drop_layout.addWidget(select_btn)
        
        # 创建拖放区域容器
        drop_area = QWidget()
        drop_area.setLayout(drop_layout)
        drop_area.setMinimumHeight(200)
        drop_area.setAcceptDrops(True)
        drop_area.dragEnterEvent = self._drag_enter_event
        drop_area.dropEvent = self._drop_event
        
        parent_layout.addWidget(drop_area)
        
    def _create_video_list(self, parent_layout):
        """创建视频列表"""
        # 列表标题
        title_label = QLabel("已导入的视频")
        title_label.setObjectName("sectionTitle")
        title_label.setProperty("class", "section-title")
        parent_layout.addWidget(title_label)
        
        # 视频列表
        self.video_list = QListWidget()
        self.video_list.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
        parent_layout.addWidget(self.video_list)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        parent_layout.addWidget(self.progress_bar)
        
    def _create_bottom_buttons(self, parent_layout):
        """创建底部按钮"""
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(10)
        
        # 删除按钮
        delete_btn = QPushButton("删除选中")
        delete_btn.clicked.connect(self._delete_selected)
        button_layout.addWidget(delete_btn)
        
        # 清空按钮
        clear_btn = QPushButton("清空列表")
        clear_btn.clicked.connect(self._clear_list)
        button_layout.addWidget(clear_btn)
        
        button_layout.addStretch()
        
        # 开始处理按钮
        process_btn = QPushButton("开始处理")
        process_btn.clicked.connect(self._start_processing)
        button_layout.addWidget(process_btn)
        
        parent_layout.addLayout(button_layout)
        
    def _apply_styles(self):
        """应用样式"""
        self.setStyleSheet(f"""
            {LABEL_STYLE}
            {BUTTON_STYLE}
            {PROGRESS_BAR_STYLE}
            {SCROLL_BAR_STYLE}
            {SECTION_TITLE_STYLE}
            {LIST_WIDGET_STYLE}
        """)
        
    def _select_files(self):
        """选择文件"""
        file_names, _ = QFileDialog.getOpenFileNames(
            self,
            "选择视频文件",
            "",
            "视频文件 (*.mp4 *.avi *.mov *.mkv);;所有文件 (*.*)"
        )
        
        if file_names:
            self._add_videos(file_names)
            
    def _add_videos(self, file_paths):
        """添加视频到列表"""
        for path in file_paths:
            item = QListWidgetItem(path)
            self.video_list.addItem(item)
            
    def _delete_selected(self):
        """删除选中的视频"""
        selected_items = self.video_list.selectedItems()
        if not selected_items:
            return
            
        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Icon.Question)
        msg.setWindowTitle("确认删除")
        msg.setText(f"确定要删除选中的 {len(selected_items)} 个视频吗？")
        msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        msg.setStyleSheet(MESSAGEBOX_STYLE)
        reply = msg.exec()
        if reply == QMessageBox.StandardButton.Yes:
            for item in selected_items:
                self.video_list.takeItem(self.video_list.row(item))
                
    def _clear_list(self):
        """清空视频列表"""
        if self.video_list.count() == 0:
            return
            
        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Icon.Question)
        msg.setWindowTitle("确认清空")
        msg.setText("确定要清空所有视频吗？")
        msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        msg.setStyleSheet(MESSAGEBOX_STYLE)
        reply = msg.exec()
        if reply == QMessageBox.StandardButton.Yes:
            self.video_list.clear()
            
    def _start_processing(self):
        """开始处理视频"""
        if self.video_list.count() == 0:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Icon.Warning)
            msg.setWindowTitle("警告")
            msg.setText("请先导入视频文件")
            msg.setStyleSheet(MESSAGEBOX_STYLE)
            msg.exec()
            return
            
        # 获取选中的视频
        selected_items = self.video_list.selectedItems()
        if not selected_items:
            msg = QMessageBox(self)
            msg.setIcon(QMessageBox.Icon.Warning)
            msg.setWindowTitle("警告")
            msg.setText("请选择要处理的视频")
            msg.setStyleSheet(MESSAGEBOX_STYLE)
            msg.exec()
            return
            
        # 获取第一个选中的视频路径
        video_path = selected_items[0].text()
        
        # 显示进度条
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        
        # 创建并启动加载线程
        self.worker = VideoLoadWorker(video_path)
        self.worker.loading_finished.connect(self._on_loading_finished)
        self.worker.error_occurred.connect(self._on_error)
        self.worker.start()
        
    def _on_loading_finished(self, video_path):
        """视频加载完成处理"""
        # 隐藏进度条
        self.progress_bar.setVisible(False)
        
        # 发送视频加载完成信号
        self.video_loaded.emit(video_path)
        
    def _on_error(self, error_msg):
        """错误处理"""
        # 隐藏进度条
        self.progress_bar.setVisible(False)
        
        # 显示错误消息
        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Icon.Critical)
        msg.setWindowTitle("错误")
        msg.setText(error_msg)
        msg.setStyleSheet(MESSAGEBOX_STYLE)
        msg.exec()
        
    def _drag_enter_event(self, event: QDragEnterEvent):
        """拖拽进入事件"""
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
            
    def _drop_event(self, event: QDropEvent):
        """拖拽释放事件"""
        urls = event.mimeData().urls()
        file_paths = [url.toLocalFile() for url in urls]
        self._add_videos(file_paths)
        
    def _on_select_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择视频文件",
            "",
            "视频文件 (*.mp4 *.avi *.mov *.mkv);;所有文件 (*.*)"
        )
        if file_path:
            self.video_list.addItem(file_path)
            self.progress_bar.setVisible(True)
            self.progress_bar.setValue(0)
            
    def _on_load_video(self):
        video_path = self.video_list.currentItem().text()
        if not video_path:
            return
            
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        self.video_list.setEnabled(False)
        self.select_btn.setEnabled(False)
        
        self.worker = VideoLoadWorker(video_path)
        self.worker.progress_updated.connect(self.progress_bar.setValue)
        self.worker.loading_finished.connect(self._on_loading_finished)
        self.worker.error_occurred.connect(self._on_error)
        self.worker.start()
        
    def _on_clear(self):
        self.video_list.clear()
        self.progress_bar.setVisible(False)
        self.clear_btn.setEnabled(False)
        self.select_btn.setEnabled(True) 